//
//  jsonWriter.m
//  iCodeMac
//
//  Created by Andrew Barry on 10/04/09.
//  Copyright 2009 Barry Computer Services. All rights reserved.
//

#import "jsonWriter.h"

@implementation jsonWriter
-(id)init {
	self = [super init];
	buffer = [NSMutableString new];
	return self;
}

-(void)writeString:(NSString *)str {
	[buffer appendString:@"\""];
	int len = [str length];
	for (int idx = 0; idx < len; idx++) {
		int ch = [str characterAtIndex:idx];
		if (ch < 32) {
			if (ch == 13)
				[buffer appendString: @"\\n"];
			else if (ch == 10)
				[buffer appendString: @"\\r"];
			else if (ch == 9)
				[buffer appendString: @"\\t"];
			else
				[buffer appendFormat: @"u%.4d", ch];
		} else if (ch == '"' || ch == '\\') {
			[buffer appendFormat: @"\\%c", ch];
		} else {
			[buffer appendFormat: @"%c", ch];
		}
	}
	[buffer appendString:@"\""];
}

-(void)writeInt:(int) v {
	[buffer appendFormat: @"%d", v];
}

-(void)writeKey:(NSString *)str {
	[self writeString: str];
	[buffer appendString:@":"];
}

-(void)writeItemSeparator {
	[buffer appendString:@","];
}

-(void)writeStartObject {
	[buffer appendString:@"{"];
}

-(void)writeEndObject {
	[buffer appendString:@"}"];
}

-(void)writeStartArray {
	[buffer appendString:@"["];
}

-(void)writeEndArray {
	[buffer appendString:@"]"];
}

-(void)writeNSArray: (NSArray *) arr {
	[self writeStartArray];
	int count = [arr count];
	for (int idx = 0; idx < count; idx++) {
		if (idx > 0)
			[self writeItemSeparator];
		[self writeNSObject:[arr objectAtIndex:idx]];
	}
	[self writeEndArray];
		
}

-(void)writeNSDictionary: (NSDictionary *) defn {
	[self writeStartObject];
	NSEnumerator *e = [defn keyEnumerator];
	NSString *key;
	bool first = true;
	while (nil != (key = [e nextObject])) {
		if (first)
			first = false;
		else
			[self writeItemSeparator];
		[self writeKey: key];
		[self writeNSObject: [defn objectForKey:key]];
		
	}
	[self writeEndObject];
}

-(void)writeNSObject: (NSObject *) obj {
	if ([obj isKindOfClass:[NSArray class]])
		[self writeNSArray:(NSArray *) obj];
	else if ([obj isKindOfClass:[NSDictionary class]])
		[self writeNSDictionary:(NSDictionary *) obj];
	else if ([obj isKindOfClass:[NSNumber class]])
	{
		CFNumberType ct = CFNumberGetType((CFNumberRef) obj);
		if (ct == kCFNumberCharType)
		{
			if ([(NSNumber *) obj boolValue])
				[buffer appendString:@"true"];
			else
				[buffer appendString:@"false"];
		}
		else
			[self writeInt:[(NSNumber *) obj intValue]];
	}
	else if ([obj isKindOfClass:[NSString class]])
		[self writeString:(NSString *) obj];
	else
		[buffer appendString: @"null"];
}

-(NSString *)finish {
	return buffer;
}

@end
